/*
 * Copyright (c) 2021-2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ffmpeg.ohos.sample.util;

import ohos.app.Context;
import ohos.app.Environment;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ResUtil {
    public static String getMediaInputFilePath(Context context, String file_name) {
        String path = "";
        RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry("resources/base/media/" + file_name);
        if (rawFileEntry != null) {
            try {
                Resource resource = rawFileEntry.openRawFile();
                File f = new File(context.getExternalFilesDir(Environment.DIRECTORY_MUSIC) + File.separator + file_name);
                if (!f.exists()) {
                    FileOutputStream fos = new FileOutputStream(f);
                    byte[] b = new byte[1024];
                    int length = 0;
                    while ((length = resource.read(b)) != -1) {
                        fos.write(b, 0, length);
                    }
                }
                path = f.getPath();
                Log.d(path, " exist=" + f.exists());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;
    }
}
